//
//  MyCardController.m
//  WuJieLive
//
//  Created by 张瀚坤 on 2017/11/8.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "MyCardController.h"
#import "PayForPasswordView.h"
#import "BankCardModel.h"
#import "CardCell.h"
#import "BindCardController.h"

@interface MyCardController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic , strong) NSArray * colorArray;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (nonatomic , strong)PayForPasswordView * payForView;

@property (nonatomic , strong) NSMutableArray * dataArray;

@end

@implementation MyCardController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)setNavi
{
    self.title = @"我的银行卡";
    [self.rightBtn setTitle:@"管理" forState:(UIControlStateNormal)];
    [self.rightBtn setTitle:@"完成" forState:(UIControlStateSelected)];
}

-(void)rightBtnAction:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"管理"]) {
        [self.tableview setEditing:YES animated:YES];
        [sender setTitle:@"完成" forState:(UIControlStateNormal)];
    }else
    {
        [self.tableview setEditing:NO animated:YES];
        [sender setTitle:@"管理" forState:(UIControlStateNormal)];
    }
    self.bottomView.hidden = self.tableview.editing;
}

//- (void)setEditing:(BOOL)editing animated:(BOOL)animated
//{
//    [super setEditing:editing animated:animated];
//    [self.tableview setEditing:editing animated:animated];
//    if (self.tableview.editing) {
//        [self.rightBtn setTitle:@"完成" forState:(UIControlStateNormal)];
//    }else
//    {
//        [self.rightBtn setTitle:@"管理" forState:(UIControlStateNormal)];
//    }
//}

-(void)setUI
{
    self.dataArray = [NSMutableArray array];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.tableview registerNib:[UINib nibWithNibName:@"CardCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.tableview.rowHeight = 75;
}


-(void)setData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary * dict = @{@"token":self.userToken};
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@//bank-bind/index",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            for (int i = 0; i < [responseObject[@"data"] count]; i ++) {
                BankCardModel * model = [[BankCardModel alloc]init];
                [model setValuesForKeysWithDictionary:[responseObject objectForKey:@"data"][i]];
                [self.dataArray addObject:model];
            }
            [self.tableview reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.bgView.backgroundColor = self.colorArray[indexPath.row % 3];
    BankCardModel * model = self.dataArray[indexPath.row];
    [cell bindDataWithModel:model];
    return cell;
}

-(NSArray *)colorArray
{
    if (!_colorArray) {
        _colorArray = @[Color(247, 98, 96),Color(69, 138, 217),Color(62, 179, 159)];
    }
    return _colorArray;
}
- (IBAction)addCardAction:(id)sender {
    BindCardController * vc = [[BindCardController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing) {
        return YES;
    }
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    BankCardModel * model = self.dataArray[indexPath.row];
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController * vc = [UIAlertController alertControllerWithTitle:@"" message:@"您确定要将银行卡解除绑定吗？" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction * done = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf.payForView.tf showKeyboard];
            [weakSelf.view addSubview:weakSelf.payForView];
            weakSelf.payForView.tf.passwordDidChangeBlock = ^(NSString *password) {
                if (password.length == 6) {
                    
                    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    NSDictionary * dict = @{@"token":self.userToken,@"bank_bind_ids":model.bank_bind_id,@"pay_password":password};
                    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@bank-bind/unbind-bank-card",BaseUrl] para:dict success:^(BOOL isSuccess, id responseObject) {
                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                        if (isSuccess) {
                            [weakSelf.payForView removeFromSuperview];
                            [weakSelf.dataArray removeObjectAtIndex:indexPath.row];
                            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
                            [tableView setEditing:NO animated:YES];
                            [weakSelf.rightBtn setTitle:@"管理" forState:(UIControlStateNormal)];
                            weakSelf.bottomView.hidden = NO;
                            [tableView reloadData];
                        }
                    }
                               failure:^(NSError *error) {
                        [MBProgressHUD hideHUDForView:self.view animated:YES];
                    }];
                }
                
            };
        }];
        UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [vc addAction:done];
        [vc addAction:cancle];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"移除";
}

- (PayForPasswordView *)payForView
{
    if (!_payForView) {
        _payForView = [[[NSBundle mainBundle] loadNibNamed:@"PayForPasswordView" owner:self options:nil] firstObject];
        _payForView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
    return _payForView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
